package com.eldos.ownerinfo;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.preference.*;
import android.view.KeyEvent;
import android.content.pm.PackageManager;
import android.telephony.TelephonyManager;

import static android.view.KeyEvent.KEYCODE_BACK;

public class OwnerInfoWidgetConfigure extends PreferenceActivity {

	public boolean isPhone() throws NullPointerException
	{
		PackageManager packageManager = this.getPackageManager();
		boolean phone = (packageManager != null && ((packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) || packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_GSM) || packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA))));
		if (!phone)
		{
			TelephonyManager tm=(TelephonyManager ) this.getSystemService(Context.TELEPHONY_SERVICE);
			phone = (tm != null) && (tm.getNetworkType() != TelephonyManager.NETWORK_TYPE_UNKNOWN);
		}
		return phone;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

		addPreferencesFromResource(R.xml.preferences);
        setResult(RESULT_CANCELED);
		if (isPhone() == false)
		{
			// hide certain controls
			PreferenceCategory mCategory = (PreferenceCategory) findPreference("cat_owner_details");
			EditTextPreference mPref = (EditTextPreference) findPreference("prefPhoneNumber");
			mCategory.removePreference(mPref);
			mPref = (EditTextPreference) findPreference("prefSMSNumber");
			mCategory.removePreference(mPref);

			mCategory = (PreferenceCategory) findPreference("cat_widget_info");
			ListPreference mListPref = (ListPreference) findPreference("prefAction");
			mCategory.removePreference(mListPref);
		}
    }

	@Override
    protected void onRestoreInstanceState(Bundle state) {
        super.onRestoreInstanceState(state);
    }

	public void notifyWidget(){

	    // this is the intent broadcast/returned to the widget
	    Intent updateIntent = new Intent(this, OwnerInfoWidget.class);
	    updateIntent.setAction(OwnerInfoConst.broadcastActionUpdate);
	    sendBroadcast(updateIntent);
        setResult(RESULT_OK);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode== KEYCODE_BACK /*|| keyCode==KeyEvent.KEYCODE_HOME*/) {
	        notifyWidget();
	    }
	    return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		notifyWidget();
	}

}
